package com.umessage.common.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.umessage.hotel.domain.WxCfg;
import com.umessage.hotel.service.WxCfgService;
import com.umessage.hotel.util.HttpUtil;

/* *
 * @Author tomsun28
 * @Description 
 * @Date 18:07 2018/3/3
 */
public class JwtMemberRealm extends AuthorizingRealm {

	@Autowired
	private WxCfgService wxCfgService;

	public Class<?> getAuthenticationTokenClass() {
		return JwtMemberToken.class;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		info.addStringPermission("hotel:get");
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		if (!(authenticationToken instanceof JwtMemberToken)) {
			return null;
		}

		// 通过code可以换取openid，认为登录成功
		JwtMemberToken jwtToken = (JwtMemberToken) authenticationToken;

		WxCfg wxcfg = wxCfgService.queryWxCfg(jwtToken.getHotelId(), "1");//1：会员端
		JSONObject userInfo = HttpUtil.getWXUserInfo((String) jwtToken.getCredentials(), wxcfg);
		String openid = userInfo.getString("openid");
		if (openid == null) {
			throw new AuthenticationException("invalid code");
		}

		return new SimpleAuthenticationInfo(openid, jwtToken.getCredentials(), this.getName());
	}
}
